﻿using System.Drawing;
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using SharpDX.Windows;
using System.Windows.Forms;
using Device = SharpDX.Direct3D11.Device;

namespace MikadoShooter
{
    public class DXWindow : Component
    {
        private readonly Size orgSize;
        private readonly Point orgLocation;
        private RenderTargetView renderView;
        public RenderForm RenderForm { get; private set; }
        public Device Device { get; private set; }
        public SwapChain SwapChain { get; private set; }
        public MouseHandler MouseHandler { get; private set; }

        public RenderTargetView RenderView
        {
            get { return renderView; }
            private set { renderView = value; }
        }

        public DXWindow(RenderForm renderForm, Device device, SwapChain swapChain)
        {
            MouseHandler = new MouseHandler();
            RenderForm = ToDispose(renderForm);
            Device = ToDispose(device);
            SwapChain = ToDispose(swapChain);
            RenderView = ToDispose(GameHelper.GetTargetView(Device));

            orgSize = RenderForm.Size;
            orgLocation = RenderForm.Location;

            RenderForm.MouseDown += MouseHandler.MouseDown;
            RenderForm.MouseUp += MouseHandler.MouseUp;
            RenderForm.Resize  += (sender, arg) =>
            {
                ComObject.Dispose(ref renderView);
                SwapChain.ResizeBuffers(1, RenderForm.ClientSize.Width, RenderForm.ClientSize.Height, Format.Unknown, SwapChainFlags.None);
                GameHelper.SetRenderTarget(Device, SwapChain, RenderForm);
                RenderView = ToDispose(GameHelper.GetTargetView(Device));
            };

            RenderForm.KeyDown += (sender, arg) =>
            {
                switch (arg.KeyCode)
                {
                    case Keys.Escape:   //Exit
                        ((RenderForm)sender).Close();
                        break;
                    case Keys.Space:    //Orginal size
                        ((RenderForm) sender).Size = orgSize;
                        ((RenderForm) sender).Location = orgLocation;
                        break;
                }
            };
        }

        public void ResizeStringTexture(Effect effect, Level level)
        {
            if (level.MessageBox.IsMessage())
                RenderForm.Resize += (sender, arg) => GameHelper.EffectStringTexture(effect, this, level.MessageBox.Text);
        }
    }
}